package com.test.controller;

import com.test.entity.DataJson;
import com.test.entity.ImgInfo;
import com.test.service.ImgInfoService;
import com.test.utils.UploadUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * @author welcome
 * 描述: 上传的controller！
 */
@RestController
@RequestMapping("upload")
@CrossOrigin
public class UploadController {

    @Resource
    ImgInfoService service;

    @PostMapping("image")
    public DataJson image(MultipartFile file){
        //调用工具类完成图片上传

        String imagePath = UploadUtils.upload(file);

        System.out.println(imagePath);
        DataJson dataJson = new DataJson();
        if (imagePath != null){
            //创建一个HashMap用来存放图片路径
            HashMap hashMap = new HashMap();
            hashMap.put("src",imagePath);
            dataJson.setCode(0);
            dataJson.setMsg("上传成功");
            dataJson.setData(hashMap);
        }else{
            dataJson.setCode(0);
            dataJson.setMsg("上传失败");
        }
        return dataJson;
    }


    @PostMapping ("addImage")
    public Boolean addImage(String imageDescribe,String imagePath){
        ImgInfo img1=new ImgInfo();
        img1.setImgAddress(imagePath);
        img1.setImgDes(imageDescribe);
        Integer insert = service.insert(img1);
        System.out.println("图片描述："+imageDescribe);
        System.out.println("图片地址："+imagePath);
        System.out.println();
        return insert>0?true:false;
    }

    @GetMapping("deleteImage")
    public Boolean deleteImage(Integer imgId){
        Integer i=0;
        ImgInfo imgInfo = service.selectById(imgId);
        if (imgInfo!=null){
            i = service.deleteById(imgId);
        }
        String str1=imgInfo.getImgAddress();
        String str2 = str1.substring(str1.lastIndexOf("/")+1);

        UploadUtils.delete(str2);
        return i>0?true:false;
    }
}
